<?php

namespace app\admin\controller\kuyou;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Shared\Date as PHPExcel_Shared_Date;
use fast\Tree;

/**
 * 工厂管理
 *
 * @icon fa fa-circle-o
 */
class Factory extends Backend
{
    /**
     * Customers模型对象
     * @var \app\admin\model\kuyou\Factory
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $setData = (new Goods())->getSetData();
        $this->assign('set', $setData['setList']);
        $this->assignconfig('set', $setData['setList']);
        $this->assign('nowmenu', $setData['nowmenu']);

        $this->model = new \app\admin\model\kuyou\Factory;
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where('factory.shop_id', $this->shop_id)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $params['account_time'] = strtotime($params['account_time']);
                $params['need_receive_account'] = round(((float)$params['receive_account'] - (float)$params['opening_prepayment']), 4);

                $data = [];
                $user = $this->request->post("user/a");
                if (empty($user['first'])) {
                    $this->error('请填写联系人');
                } else {
                    $default = '';
                    foreach ($user['first'] as $user_first_k => $user_first_v) {
                        if (isset($user['name'][$user_first_k]) && !empty($user['name'][$user_first_k]) && isset($user['mobile'][$user_first_k]) && !empty($user['mobile'][$user_first_k])) {
                            if ($user_first_v == 1 && $default !== '') {
                                $this->error('只能选择一个首要联系人');
                            }
                            if ($user_first_v == 1) {
                                $default = $user_first_k;
                            }
                            $data[] = [
                                'shop_id' => $this->shop_id,
                                'first_connect_name' => $user['name'][$user_first_k],
                                'first_connect_mobile' => $user['mobile'][$user_first_k],
                                'first_connect_phone' => $user['phone'][$user_first_k],
                                'qq_wx_email' => $user['qqnum'][$user_first_k],
                                'connect_address' => $user['address'][$user_first_k],
                                'is_first' => $user['first'][$user_first_k],
                                'createtime' => time(),
                                'updatetime' => time(),
                            ];
                        }
                    }
                    if (empty($data)) {
                        $this->error('请完善联系人信息');
                    }
                }
                $default = $default === '' ? 0 : $default;
                $data[$default]['is_first'] = 1;
                $params['connet_name'] = $user['name'][$default];
                $params['customer_mobile'] = isset($user['mobile'][$default]) ? $user['mobile'][$default] : '';
                $params['customer_phone'] = isset($user['phone'][$default]) ? $user['phone'][$default] : '';
                $params['qq_wx_email'] = isset($user['qqnum'][$default]) ? $user['qqnum'][$default] : '';
                $params['getgoods_address'] = isset($user['address'][$default]) ? $user['address'][$default] : '';

                if (Db::name('kuyou_factory')->where('shop_id', $this->shop_id)->where((new Goods())->setWhere(['customer_code' => trim($params['customer_code'])]))->find()) {
                    $this->error('工厂编号已占用');
                }

                $result = false;
                Db::startTrans();
                try {
                    $params['shop_id'] = $this->shop_id;
                    $result = Db::name('kuyou_factory')->insertGetId($params);

                    foreach ($data as $data_k => $data_v) {
                        $data[$data_k]['customers_code'] = trim($params['customer_code']);
                        $data[$data_k]['sid'] = $result;
                    }
                    Db::name('kuyou_factory_user')->insertAll($data);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $code = (new Goods())->getCodes('', 37);
        $this->view->assign("code", $code);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $params['account_time'] = strtotime($params['account_time']);
                $params['need_receive_account'] = round(((float)$params['receive_account'] - (float)$params['opening_prepayment']), 4);

                $data = [];
                $user = $this->request->post("user/a");
                if (empty($user['first'])) {
                    $this->error('请填写联系人');
                } else {
                    $default = '';
                    foreach ($user['first'] as $user_first_k => $user_first_v) {
                        if (isset($user['name'][$user_first_k]) && !empty($user['name'][$user_first_k]) && isset($user['mobile'][$user_first_k]) && !empty($user['mobile'][$user_first_k])) {
                            if ($user_first_v == 1 && $default !== '') {
                                $this->error('只能选择一个首要联系人');
                            }
                            if ($user_first_v == 1) {
                                $default = $user_first_k;
                            }
                            $data[] = [
                                'shop_id' => $this->shop_id,
                                'first_connect_name' => $user['name'][$user_first_k],
                                'first_connect_mobile' => $user['mobile'][$user_first_k],
                                'first_connect_phone' => $user['phone'][$user_first_k],
                                'qq_wx_email' => $user['qqnum'][$user_first_k],
                                'connect_address' => $user['address'][$user_first_k],
                                'is_first' => $user['first'][$user_first_k],
                                'createtime' => time(),
                                'updatetime' => time(),
                            ];
                        }
                    }
                    if (empty($data)) {
                        $this->error('请完善联系人信息');
                    }
                }
                $default = $default === '' ? 0 : $default;
                $data[$default]['is_first'] = 1;
                $params['connet_name'] = $user['name'][$default];
                $params['customer_mobile'] = isset($user['mobile'][$default]) ? $user['mobile'][$default] : '';
                $params['customer_phone'] = isset($user['phone'][$default]) ? $user['phone'][$default] : '';
                $params['qq_wx_email'] = isset($user['qqnum'][$default]) ? $user['qqnum'][$default] : '';
                $params['getgoods_address'] = isset($user['address'][$default]) ? $user['address'][$default] : '';

                if (Db::name('kuyou_factory')->where('shop_id', $this->shop_id)->where(['customer_code' => trim($params['customer_code']), 'id' => ['<>', $ids]])->find()) {
                    $this->error('编号已占用');
                }

                $result = false;
                Db::startTrans();
                try {
                    Db::name('kuyou_factory_user')->where('shop_id', $this->shop_id)->where(['sid' => $ids])->delete();
                    $result = Db::name('kuyou_factory')->where('shop_id', $this->shop_id)->where(['id' => $ids])->update($params);
                    foreach ($data as $data_k => $data_v) {
                        $data[$data_k]['customers_code'] = trim($params['customer_code']);
                        $data[$data_k]['sid'] = $ids;
                    }
                    Db::name('kuyou_factory_user')->insertAll($data);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);

        $user = Db::name('kuyou_factory_user')->where('shop_id', $this->shop_id)->where(['sid' => $ids])->select();
        $this->view->assign("user", $user);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            foreach ($list as $list_k => $list_v) {
                $order_info = Db::name('kuyou_outsourcing')->where('shop_id', $this->shop_id)->where(['customers_id' => $list_v['id']])->field('id')->find();
                if (!empty($order_info)) {
                    $this->error($list_v['customer_name'] . '已有委外加工单，不可删除');
                }
            }

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += Db::name('kuyou_factory')->where('shop_id', $this->shop_id)->where(['id' => $v['id']])->delete();
                    Db::name('kuyou_factory_user')->where('shop_id', $this->shop_id)->where(['sid' => $v['id']])->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
